package snaptest.repo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class FileIO {

	public void save(String path, String content) throws IOException {
		FileWriter fileWriter = new FileWriter(path);
		fileWriter.write(content);
		fileWriter.flush();
		fileWriter.close();
	}

	public void createFile(String directoryPath, String fileName) throws IOException {
		File dir = new File(directoryPath);
		dir.mkdirs();
		File file = new File(dir, fileName);
		file.createNewFile();
	}

	public String load(String path) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(new File(path)));
		return loadFileContent(reader);
	}

	private String loadFileContent(BufferedReader reader) throws IOException {
		String nextLine = reader.readLine();
		StringBuilder sb = new StringBuilder();
		while (nextLine != null) {
			sb.append(nextLine);
			nextLine = reader.readLine();
			sb.append(nextLine != null ? "\n" : "");
		}
		reader.close();
		return sb.toString();
	}

	public boolean fileExistOnClassPath(String path) {
		return classLoader().getResource(path) != null;
	}

	public boolean fileExists(String path) {
		return new File(path).exists();
	}

	private ClassLoader classLoader() {
		return getClass().getClassLoader();
	}

}
